#include <stdio.h>
#include <sys/types.h> 
#include <sys/socket.h> //包含套接字的函数库 
#include <netinet/in.h> //包含AF_INET的相关结构 
#include <arpa/inet.h> //包含AF_INET的操作函数 
#include <unistd.h> 
#include <stdlib.h> 
#include <stdio.h> 
#include <string.h>
#include <fcntl.h>

#define PORT 666
#define KEY_LEN 52
#define VALUE_LEN 100
#define BUF_LEN 156
struct msg
{
	int data_len;
	char name[KEY_LEN];
	char data[VALUE_LEN];
};

int main(int argc ,char* args[]){

	//printf("%s\n",args[1] );
	int c_fd;
	struct sockaddr_in addr;
	//消息长度
	int databytes = 0;
	//消息
	char sendbuf[BUF_LEN];
	char recvbuf[BUF_LEN];
	//创建套接字
	c_fd = socket(AF_INET,SOCK_STREAM,0);
	if(c_fd < 0){
		perror("创建套接字失败！");
		return -1;
	}

	//初始化套接字
	addr.sin_family = AF_INET;
	addr.sin_port = htons(PORT);
	/*char ip[20];
	printf("输入ｉｐ：\n");
	scanf("%s",ip);*/
	//94.191.2.228
	addr.sin_addr.s_addr = inet_addr("94.191.2.228");
	addr.sin_addr.s_addr = inet_addr("127.0.0.1");
	//连接
	if( connect(c_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0){
		perror("连接失败！");
		return -1;
	}

	while(1){
	
		char para[50];
		printf("请输入命令（instruct）\n");
		scanf("%s",para);
		strncpy(sendbuf,para,strlen(para));
		send(c_fd,sendbuf,strlen(para),0);
		int flag=0;
		int j=0;
		while(flag = recv(c_fd,recvbuf,sizeof(struct msg),0)){
			if(flag<sizeof(struct msg)){//有可能接收不完
				int recv_len = flag;
				flag = recv(c_fd,recvbuf+recv_len,sizeof(struct msg)-recv_len,0);
				//printf("###########################################################\n");
			}
			if(strncmp(recvbuf,"finish",6)==0)break;
			
			struct msg ss;
			
			memset(&ss,0,sizeof(struct msg));
			memcpy(&ss,recvbuf,sizeof(struct msg));
			//printf("%d\n", flag);
			/*for(j=0;j<156;j++){
	
				printf("%c+%d",((char*)&ss)[j],j);
`1
			}*/
			printf("%s\n",ss.data);
			/*for(j=0;j<10;j++){
	
				printf("%c+",ss.data[j]);

			}*/
			
			memset(recvbuf,0,sizeof(struct msg));
			
			
		}
		printf("完成\n");

	}
	close(c_fd);

	return 0;
}
